<?php
class Db_Products_GroupStyles extends Common {
	protected static $tableName = TAB_GROUP_STYLES;
	protected static $dbFields = array(
		'id',
		'gs_name',
		'deleted'
	);

	public $id;
	public $gs_name;
	public $deleted;

	/**
	 * A function for pagination
	 * @param string $limit A string containing the SQL 'LIMIT' clause
	 * @param string $searchSql A string containing an SQL condition, i.e. '`foo` LIKE 'bar' OR `foo` LIKE '%baz%'
	 * @param string $orderBy A string containing an SQL 'ORDER BY' clause
	 * @return bool|array
	 */
	public static function loadAll($limit, $searchSql = '', $orderBy = '') {
		if (empty($searchSql)) {
			$searchSql = '1=1';
		}
		if (empty($orderBy)) {
			$orderBy = ' ORDER BY `gs_name` ASC ';
		}
		$sql = "SELECT `gs`.`id`, `gs`.`gs_name`, `p`.`id` AS `product_id` FROM ?f gs
				LEFT JOIN ?f p ON `p`.`p_group_style` = `gs`.`id`
				WHERE `gs`.`deleted` = 0 AND {$searchSql} GROUP BY `gs`.`id` {$orderBy} {$limit}";
		return self::$DB->select($sql,self::$tableName, TAB_PRODUCTS);
	}

	/**
	 * Will return all the group styles for a product
	 * @param int $productId The id of the product. Pass a null or skip that argument to get all group styles
	 * @return bool|array
	 */
	public static function loadForProduct($productId = null) {
		$sql = "SELECT `gs`.`id`, `gs`.`gs_name` FROM ?f gs";
		if ($productId && (int) $productId > 0) {
			$sql .= " LEFT JOIN ?f `p` ON `p`.`deleted` = 0 AND `gs`.`id` = `p`.`p_group_style` AND `p`.`id` = ?d";
		}
		$sql .= " WHERE `gs`.`deleted` = 0";
		return self::find($sql, self::$tableName, TAB_PRODUCTS, $productId);
	}

	public static function getProductCategories($productId){
		$sql = "SELECT `id`, `pc_name`";
		if (!empty($productId) && is_numeric($productId)) {
			$sql .= ", `prc_category_id`";
		}
		$sql .= " FROM ?f";
		if (!empty($productId) && is_numeric($productId)) {
			$sql .= " LEFT JOIN ?f ON `id`=`prc_category_id` AND `prc_product_id`=?";
		}
		$sql .= " WHERE deleted=0";
		if (!empty($productId) && is_numeric($productId)) {
			$sql .= " ORDER BY prc_is_default DESC";
		}
		return self::findArray($sql, TAB_CATEGORIES, TAB_PRODUCT_CATEGORIES, $productId);
	}

	public static function getTotalElements($sqlCondition = '1=1') {
		if (empty($sqlCondition)) {
			$sqlCondition = '1=1';
		}
		return self::$DB->selectCell("SELECT COUNT(*) FROM ?f gs
			WHERE `gs`.`deleted` = 0 AND {$sqlCondition};",self::$tableName);
	}
}